<html>
<body>

<h1>CS 143: Project 1A - Calculator</h1>

<h3>Troy Tabrilla<br>103786596</h3>

<p>Input your expression below. Only numbers and basic operators (+, -, *, /) 
are accepted.</p>

<form action="calculator.php" method="post">
<input type="text" name="input">
<input type="submit" value="Calculate">
</form>

<?php
	// Hide raw PHP errors.
	function errHandler($errno)
	{
		// Ignore run-time errors.
		if($errno != 8)
			echo "Error evaluating expression.<br>";
	}
	set_error_handler("errHandler");
	
	$input = $_POST['input'];
	
	// Reject expressions with invalid characters (spaces are valid).
	if(preg_match("#[^0-9\.\-+*/\ ]#", $input, $match))
		echo "Invalid expression: ".$input.". Only numeric 
		characters and +, -, *, or / are acceptable.";
		
	/* Reject expressions with multiple operands separated by spaces,
	excluding positive/negative signs. */
	else if(preg_match("#[\-+*/]\ *[*/]#", $input, $match))
		echo "Invalid expression: ".$input.". Multiple operands 
		are not acceptable.";
		
	/*Rject expressions with double positive signs explicitly. */
	else if(preg_match("#[+]{2}#", $input, $match))
		echo "Invalid expression: ".$input.". Multiple operands 
		are not acceptable. Separate your positive signs if you want to 
		add a positive number, i.e. 1+ +1.";
		
	/* Reject expressions with double negative signs explicitly. */
	else if(preg_match("#\-{2}#", $input, $match))
		echo "Invalid expression: ".$input.". Multiple operands
		are not acceptable. Separate your negative signs if you want to 
		subtract a negative number, i.e. 1- -1.";
	
	/* Reject triple or more '+-' or '-+' substrings. */
	else if(preg_match("#[+\-]{3}#", $input, $match))
		echo "Invalid expression: ".$input.".";
		
	// Reject expressions that don't end with a number.
	else if(preg_match("#[\-+*/]\ *$#", $input, $match))
		echo "Invalid expression: ".$input.". Missing an argument.";
		
	// Reject expressions that don't start with a number, plus, or minus.
	else if(preg_match("#^\ *[*/]#", $input, $match))
		echo "Invalid expression: ".$input.". Missing an argument.";
		
	// Otherwise, expression is acceptable, so try to evaluate and print result.
	else
	{
		// Make sure input has at least 1 number.
		if(preg_match("#[0-9]#", $input, $match))
		{
			eval("\$ans=$input;");
			echo $input." = ".$ans;
		}
		
		// Will print nothing if no number inputted.
	}	
?>

</body>
</html>